package com.znxz.hzqiuxm.ziniublog.user.gateways.controller;

import com.znxz.hzqiuxm.ziniublog.global.common.SysConst;
import com.znxz.hzqiuxm.ziniublog.global.common.JsonResult;
import com.znxz.hzqiuxm.ziniublog.global.security.JwtTokenUtil;
import com.znxz.hzqiuxm.ziniublog.user.gateways.vo.UserVO;
import com.znxz.hzqiuxm.ziniublog.user.domain.entity.UserDO;
import com.znxz.hzqiuxm.ziniublog.user.domain.valobj.JwtUser;
import com.znxz.hzqiuxm.ziniublog.user.domain.services.UserServices;
import lombok.extern.slf4j.Slf4j;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

/**
 * Copyright © 2018年 ziniuxiaozhu. All rights reserved.
 *
 * @Author 临江仙 hzqiuxm@163.com
 * 无需权限校验的方法
 * @Date 2018/9/2 16:20
 */
@Controller
@Slf4j
@RequestMapping("/auth")
public class AuthController extends BaseController {

    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Value("${jwt.expiration}")
    private String expiration;
    @Value("${jwt.expirationTime}")
    private long expirationTime;

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private UserServices userServices;
    @Autowired
    private Mapper mapper;
    @Autowired
    PasswordEncoder passwordEncoder;


    @GetMapping
    public String index(){

        log.info("index page .......");
        return "index.html";
    }

    @GetMapping("/reg")
    public String reg(){

        log.info("reg page .......");
        return "reg.html";
    }

    /**
     * 用户名或手机号带密码登录，登录成功后返回一个token
     * @param response
     * @param loginName
     * @param password
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public ModelMap login(HttpServletResponse response, String loginName, String password){

        log.info("loginName : {} , and password : {} ",loginName,password);
        if (StringUtils.isEmpty(loginName) || StringUtils.isEmpty(password)){
            return getFailResult(SysConst.ReturnCode.F_201, "用户名或密码不能为空哦");
        }

        UsernamePasswordAuthenticationToken upAuthToken = new UsernamePasswordAuthenticationToken(loginName, password);
        final Authentication authentication = authenticationManager.authenticate(upAuthToken);

        System.out.println("------------------login------------------");
        SecurityContextHolder.getContext().setAuthentication(authentication);
        JwtUser jwtUser = (JwtUser) authentication.getPrincipal();
        response.addHeader(this.tokenHead, jwtTokenUtil.generateToken(jwtUser));
        response.addHeader(this.expiration, this.expirationTime*JwtTokenUtil.A_MINUTE + "");

        return getSuccessResult(jwtUser);
    }


    /**
     * 注册用户
     * @param userVO
     * @return
     */
    @PostMapping("/user")
    @ResponseBody
    public JsonResult<UserDO> register(@RequestBody @Validated UserVO userVO){

        UserDO userDO = mapper.map(userVO, UserDO.class);
        userDO.setPassword(passwordEncoder.encode(userVO.getPassword()));

        return new JsonResult<>(userServices.addUser(userDO));
    }
}
